<script setup>
import {useMemberStore} from '/stores/modules/member.js'
import {reqUploadFile,reqUpdateAvatar} from '../api/user.js'
import { getCurrentInstance,ref } from 'vue';
const memberStore = useMemberStore()
const {profile} = memberStore
const {proxy} = getCurrentInstance()
// console.log(memberStore);

const chooseAvatar = async(event)=>{
	// console.log(event);
	// 获取新头像的临时路径
	const {avatarUrl} = event.detail
	const res = await reqUploadFile(avatarUrl,'file')
	// console.log(res);
	profile.userInfo.headimgurl=res.data
	memberStore.setProfile(profile.userInfo)
}
// 更新用户信息
const saveNickname = async()=>{
	const res = await reqUpdateAvatar(profile.userInfo)
	// console.log(res);
	profile.userInfo.nickname=tempName.value
	memberStore.setProfile(profile.userInfo)
	if(res.code ===200){
		proxy.$toast({
			title:'保存成功'
		})
	}
}
const inputDialog = ref(null)
const  updateName = ()=>{
	inputDialog.value.open()
}
let tempName = ref(profile.userInfo.nickname)
const dialogInputConfirm =async(e)=>{
	// console.log(e);
	if(e.length>=3&&e.length<=10){
		tempName.value=e
		inputDialog.value.close()
	}else{
		proxy.$toast({
			title:'输入的数据长度有误！',
			duration:800
		})
	}
}
const dialogInputClose=()=>{
	inputDialog.value.close()
}
</script>

<template>
  <view class="profile">
	<uni-list>
		<uni-list-item showArrow>
			<template v-slot:header>
				<text class="avatar">头像</text>
			</template>
			<template v-slot:footer>
				<button class="ava-btn" open-type="chooseAvatar" @chooseavatar="chooseAvatar">
					<image :src="profile.userInfo.headimgurl ||'../../static/Jerry.png'" class="img"></image>
				</button>				
			</template>
		</uni-list-item>
	</uni-list>
	<uni-list class="uni-list1">
		<uni-list-item title="昵称"  showArrow>
			<template v-slot:footer>
				<text class="userName" @click="updateName">{{profile.userInfo.nickname || '尚硅谷'}}</text>
			</template>
		</uni-list-item>
	</uni-list>
	<view class="save">
		<button type="warn" class="save-btn" @click="saveNickname">保存</button>
	</view>
	<uni-popup ref="inputDialog" type="dialog">
		<uni-popup-dialog
			mode="input" title="请输入新的用户名" 
			v-model="tempName"
			:before-close="true"			
			@close="dialogInputClose"
			@confirm="dialogInputConfirm">
		</uni-popup-dialog>
	</uni-popup>
  </view>
</template>

<style lang="scss" scoped>
.profile{
	padding: 0 16rpx;
	.save{
		text-align: center;
		.save-btn{
			font-size: 26rpx;
			height: 80rpx;
			width: 500rpx;
			border-radius: 20rpx;
			line-height: 80rpx;
		}
	}
	.ava-btn{
		width: 60rpx;
		height: 60rpx;
		position: relative;
		.img{
			position: absolute;
			left: 0;
			
			width: 61rpx;
			height: 61rpx;
		}
	}
	:deep(.uni-list){
		margin: 20rpx 0;
	};
	.avatar{
		font-size: 28rpx;
		line-height: 60rpx;
	}
	.userName{
		font-size: 24rpx;
		color: #b6b6b6;
	}
}

</style>
